// 游客登录服务
import { login } from '@/api';
import { useAppStore, useUserStore } from '@/stores';
import { getUuid } from '@/utils/utils';

// 游客账号配置
const GUEST_CREDENTIALS = {
  username: 'guest',
  password: 'Jykj@301117',
};

export class GuestService {
  private static instance: GuestService;
  private isGuestLoggedIn = false;

  static getInstance(): GuestService {
    if (!GuestService.instance) {
      GuestService.instance = new GuestService();
    }
    return GuestService.instance;
  }

  // 检查是否为游客登录状态
  isGuest(): boolean {
    return this.isGuestLoggedIn;
  }

  // 游客自动登录
  async autoLoginAsGuest(): Promise<boolean> {
    try {
      const userStore = useUserStore();
      const appStore = useAppStore();

      // 如果已经有token，不需要重复登录
      if (userStore.token && !this.isGuestLoggedIn) {
        return true;
      }

      console.log('正在进行游客自动登录...');

      const res = await login({
        ...GUEST_CREDENTIALS,
        uuid: getUuid(),
      });

      if (res.code !== 0) {
        console.error('游客登录失败:', res.msg);
        return false;
      }

      // 设置token但不设置用户信息，保持页面未登录状态
      if (res.data.token) {
        userStore.setToken(res.data.token);
        this.isGuestLoggedIn = true;

        // 初始化应用数据
        const initSuccess = await appStore.initApp();
        if (!initSuccess) {
          console.error('游客登录后初始化应用数据失败');
          return false;
        }

        console.log('游客自动登录成功');
        return true;
      }

      return false;
    }
    catch (error) {
      console.error('游客自动登录错误:', error);
      return false;
    }
  }

  // 清除游客状态
  clearGuestStatus(): void {
    this.isGuestLoggedIn = false;
  }

  // 用户主动登录时清除游客状态
  onUserLogin(): void {
    console.log('用户主动登录，清除游客状态');
    this.isGuestLoggedIn = false;
  }
}

// 导出单例实例
export const guestService = GuestService.getInstance();
